package com.anan.service.imp;

import com.alibaba.fastjson.JSONObject;
import com.anan.config.AppConfig;
import com.anan.entity.dto.UserInfoDto;
import com.anan.entity.po.UserInfo;
import com.anan.entity.query.UserInfoQuery;
import com.anan.entity.vo.UserInfoVo;
import com.anan.exception.BusinessException;
import com.anan.mapper.UserInfoMapper;
import com.anan.service.UserInfoService;
import com.anan.utils.AnanUtils;
import com.anan.utils.RedisUtils;
import com.anan.utils.Result;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * @Author: Anan
 * @email: 2328791101@qq.com
 * @project_name: anan-bookkeeping
 * @time: 2023/6/259:40
 */

@Service
public class UserInfoServiceImp implements UserInfoService {
    private static final Logger logger = LoggerFactory.getLogger(UserInfoServiceImp.class);
    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    RedisUtils<Object> redisUtils;

    @Override
    public Result login(UserInfoDto query) {
        Result result = new Result();

        UserInfo user = getUserName(query.getUserName());
        if (user == null) {
            result.setCode(400);
            result.setMsg("该用户不存在请注册");
        } else {
            UserInfoVo userInfoVo = new UserInfoVo();
            UserInfoQuery userInfoQuery = new UserInfoQuery();
            userInfoQuery.setUserName(query.getUserName());
            userInfoQuery.setPassword(AnanUtils.MD5Encryption(query.getPassword(), query.getUserName()));
            user = get(userInfoQuery);
            if (user == null) {
                result.setCode(400);
                result.setMsg("用户密码错误");
            } else {
                BeanUtils.copyProperties(user, userInfoVo);
                userInfoVo.setPassword(null);
                result.setCode(200);
                result.setMsg("登录成功");
                String token = (UUID.randomUUID().toString().toUpperCase()).replace("-", "");
                 redisUtils.put(token, userInfoVo, 60 * 60 * 24 * 7L);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("userInfo", userInfoVo);
                jsonObject.put("token", token);
                result.setData(jsonObject);
            }
        }
        return result;
    }

    @Override
    public Result register(UserInfoDto query) {
        Result result = new Result();
        UserInfo userinfo = getUserName(query.getUserName());
        if (userinfo != null) {
            throw new BusinessException(401, query.getUserName()+" 已被注册请登录");
        }
        UserInfo userInfoQuery = new UserInfo();
        userInfoQuery.setUserName(query.getUserName());
        String id = null;
        while (true){
             id = AnanUtils.DisruptSort(String.valueOf(System.currentTimeMillis()));
            UserInfo userInfo1 = getId(id);
            if (userInfo1 == null){
                break;
            }

        }
        userInfoQuery.setId(id);
        userInfoQuery.setPassword(AnanUtils.MD5Encryption(query.getPassword(), query.getUserName()));
        userInfoQuery.setAvatarName("default");
        int user = -1;
        try {
            user = insert(userInfoQuery);
        } catch (Exception e) {
            throw new BusinessException(400, "注册失败 ，请重新注册");
        }
        if (user < 0) {
            result.setCode(400);
            result.setMsg("用户注册失败");
        } else {
            result.setCode(200);
            result.setMsg("用户注册成功");
        }
        return result;
    }

    @Override
    public Result resetPassword(UserInfoDto query) {
        Result result = new Result();
        UserInfo userInfo = getUserName(query.getUserName());
        if (userInfo == null) {
            throw new BusinessException(400, " 没有查询到该账户信息，请注册");
        }
        UserInfoQuery userInfoQuery = new UserInfoQuery();
        userInfoQuery.setUserName(query.getUserName());
        userInfoQuery.setId(query.getId());
        userInfoQuery.setPassword(AnanUtils.MD5Encryption(query.getPassword(), query.getUserName()));
        int user = update(userInfoQuery);
        if (user < 0) {
            result.setCode(400);
            result.setMsg("用户密码重置失败");
        } else {
            result.setCode(200);
            result.setMsg("用户密码重置成功");
        }
        return result;
    }

    @Override
    public boolean sendCheckCode(String email) {
        try {
            String code = RandomStringUtils.random(5, false, true);
            String result = AnanUtils.emailSend(email, code, null);
            System.out.println(result);
             redisUtils.put(email, code, 5 * 60L);
            return true;
        } catch (Exception e) {
            logger.error("邮件发送失败! error:", e);
            throw new BusinessException("邮件发送失败");
        }
    }


    @Override
    public int updateAvatar(String fileName, String id) {
        UserInfoQuery userInfoQuery = new UserInfoQuery();
        userInfoQuery.setId(id);
        userInfoQuery.setAvatarName(fileName);
        int result = update(userInfoQuery);
        return result;
    }



    @Override
    public Integer insert(UserInfo query) {



        return userInfoMapper.insert(query);
    }

    @Override
    public Integer delete(UserInfoQuery query) {
        return userInfoMapper.delete(query);
    }

    @Override
    public UserInfo get(UserInfoQuery query) {
        return userInfoMapper.get(query);
    }
    @Override
    public UserInfo getUserName(String UserName) {
        UserInfoQuery userInfoQuery = new UserInfoQuery();
        userInfoQuery.setUserName(UserName);
        return userInfoMapper.get(userInfoQuery);
    }
    @Override
    public UserInfo getId(String id) {
        UserInfoQuery userInfoQuery = new UserInfoQuery();
        userInfoQuery.setId(id);
        return userInfoMapper.get(userInfoQuery);
    }


    @Override
    public List<UserInfo> list(UserInfoQuery query) {
        return userInfoMapper.list(query);
    }

    @Override
    public Integer update(UserInfoQuery query) {
        return userInfoMapper.update(query);
    }

    @Override
    public List<UserInfo> list() {
        return userInfoMapper.listUser();
    }
}
